<?php

class Admin_PositionController extends Zend_Controller_Action
{
    private $_config;
    private $_categories;
	protected $_models = array();
	
    public function init()
    {
        $album = Utils_Global::$params['album'];
        if($album == 0) {
            $this->view->bannerclzz = 'active';
        } else if($album == 2) {
            $this->view->galleryclzz = 'active';
        }
        $this->_config = Utils_Global::getConfig('admin', 'upload');
    }

    public function deleteAction()
    {
		$id = Utils_Global::$params['id'];
		$album = Utils_Global::$params['album'];
		$model = Admin_Model_Position::factory();
		$result = $model->delete($id);
		if($result) {
			$errMessage = "Xóa thành công";
		} else {
			$errMessage = "Xóa không thành công, vui lòng thử lại!";
		};
		$this->_redirect('/admin/position/list/id/?errMessage=' . $errMessage . '&album=' . $album);
    }
    
    public function listAction() {   
        $page = intval(Utils_Global::$params['page']);
        $limit = intval(Utils_Global::$params['limit']);
        $errMessage = Utils_Global::$params['errMessage'];
        $id = Utils_Global::$params['id'];
        $name = Utils_Global::$params['position_name'];
        $album = Utils_Global::$params['album'];
        if(!$album) {
            $album = 0;
        }
        if($page <= 0) {
            $page = 1;
        }
        if($limit <= 0) {
            $limit = 10;
        }
        
        $positionModel = Admin_Model_Position::factory();
        $options = array('offset' => ($page - 1) * $limit, 'limit' => $limit, 'collection' => $album);
        $options['id'] = $id;
        $options['position_name'] = $name;
		$result = $positionModel->getPositions($options);
		$this->view->positions = $result;
		$this->view->page = $page;
		$countOptions = array('id' => $id, 'position_name' => $name);
		$this->view->totalItem = $positionModel->getPositionsCount($options);
		$this->view->numRowPerPage = $limit;
		$this->view->currentUrl = $this->view->serverUrl() . $this->view->url(array()) . '?' . http_build_query($options);
		$this->view->title = "Position";
		$this->view->errMessage = $errMessage;
		$this->view->params = $options;
		if($album == 2) {
		    $this->renderScript('position/list-album.phtml');
		}
    }
    
    public function editAction()
    {
        $id = Utils_Global::$params['id'];
        $isAlbum = Utils_Global::$params['album'];
        if($id) {
            $positionModel = Admin_Model_Position::factory();
            $positions = $positionModel->getPositions(array('id' => $id));
            $isAlbum = $positions[0]['collection'];
            $this->view->position = $positions[0];
            $this->view->id = $id;
        }
        $this->view->album = $isAlbum;
        if($isAlbum == 2) {
            $this->renderScript('position/edit_album.phtml');
        }
    }
	
	/**
	 * method: update layout information
	 * Description: update layout
	 */
	 public function saveAction()
	 {
	     $id = Utils_Global::$params['id'];
	     $name = Utils_Global::$params['name'];
	     $collection = Utils_Global::$params['collection'];
	     if(!$name) {
	         Utils_Global::$params['errMessage'] = "Vui lòng nhập tên";
	         $this->_forward('edit', 'position', 'admin');
	     }
	     
	     if(!$collection) {
	         $collection = 0;
	     }
	     
	     $data = array('position_name' => $name,
	                     'collection' => $collection,
        	         'last_update' => time(),);
	     $result = $this->uploadTempImage('banner');
	     if(is_array($result) && $result) {//Luu thong tin upload
	     	$data['image'] = $result['image'];
	     }
	     
	     $positionModel = Admin_Model_Position::factory();
	     if($id) {
	         $result = $positionModel->update($id, $data);
	     } else {
	         $data['dateline'] = time();
	         $result = $positionModel->insert($data);
	     }
	     
	     if($result > 0) {
	         $this->_redirect('/admin/position/list?album=' . $collection);
	     } else {
	         $this->view->errMessage = "Có lỗi xảy ra, vui lòng thử lại";
	         $this->_forward('edit', 'position', 'admin', array('album' => $collection));
	     }
	 }

	     
	 /**
	  * upload into temp folder;
	  * @param string $category$category : article or course etc
	  * @return 0: lỗi ko xác định, -1: file type ko phù hợp, -2: size vượt quá quy định
	  *
	  * */
	 public function uploadTempImage($category) {
	 	try{
	 		$upload = new Zend_File_Transfer_Adapter_Http();
	 		$files = $upload->getFileInfo();
	 		$imagePath = $upload->getFileName();
	 		$key = $category.'AvatarUploadPath';
	 		$imageUploadPath    = $this->_config->upload->$key;
	 		$imageFileName      = '';
	 		if($files['file']) {
	 			//Check file valid
	 			if(!$files['file']['name'] || !preg_match('/jpg|jpeg|gif|png|bmp/', $files['file']['name'])) {
	 				return -1;
	 			}
	 			//Check file type is valid or not
	 			$allowTypes = $this->_config->upload->acceptedFileTypes->toArray();
	 			if(!in_array($files['file']['type'], $allowTypes)) {
	 				return -1;//Invalid file
	 			}
	 			//Check size
	 			$source_size = $files['file']['size'];
	 			if($source_size > $this->_config->upload->maxFileSizeUpload) {
	 				return -2;//Oversize
	 			}
	 			//Image chapter file name
	 			$originalImageFileName = str_replace(' ', '', basename($imagePath));
	 			$imageFileName = $originalImageFileName;
	 			//     			$ext = pathinfo($imageFileName, PATHINFO_EXTENSION);
	 			//     			$imageFileName = md5(time() . $imageFileName);
	 			//     			$imageFileName = $imageFileName . '.' . $ext;
	 
	 			$imageUploadPath = $this->createTempFolder($imageUploadPath, $originalImageFileName);
	 			
	 			$upload->setDestination($imageUploadPath);
	 
	 			//     			$upload->addFilter('Rename', array('target' => $imageUploadPath . '/' . $imageFileName));
	 			$result = $upload->receive();
	 			//Tien hanh check type 1 lan nua, make sure day la file hinh
	 			$fileType = mime_content_type($imageUploadPath . '/' . $imageFileName);
	 			if(!in_array($fileType, $allowTypes)) {
	 				unlink($imageUploadPath . '/' . $imageFileName);
	 				return -1;//Invalid file
	 			}
	 
	 			$imageSize = getimagesize($imageUploadPath . '/' . $imageFileName);
	 			if(!$imageSize) {
	 				unlink($imageUploadPath . '/' . $imageFileName);
	 				return -1;
	 			}
	 			if($imageSize[0] < $this->_config->upload->dimentionW || $imageSize[1] < $this->_config->upload->dimentionH) {
	 				unlink($imageUploadPath . '/' . $imageFileName);
	 				return -3;
	 			}
	 		} else {
	 			return -4;
	 		}
	 		 
	 		$rResult = array();
	 		if($result) {
	 			$rResult['source_size'] = $source_size;
	 			$rResult['image'] = $imageFileName;
	 			//     			$rResult['hash_folder'] = Utils_Global::hashName($originalImageFileName, 512);
	 		}
	 		 
	 		return $rResult;
	 	} catch(Exception $e) {
	 	    prBinh($e);
	 		return 0;
	 	}
	 }
	 
	 private function createTempFolder($imageUploadPath, $userName) {
	 	//If source is not existed
	 	if(!file_exists($imageUploadPath)) {
	 		mkdir($imageUploadPath);
	 	}
	 
	 	// 	 	$hashName = Utils_Global::hashName($userName, 512);
	 	// 	 	$imageUploadPath .= '/' . $hashName;
	 	// 	 	if(!file_exists($imageUploadPath)) {
	 	// 	 		mkdir($imageUploadPath);
	 	// 	 	}
	 
	 	return $imageUploadPath;
	 }

    /**
     * Get model box object	
     */
    protected function &_getModel($className)
    {
		if(isset($this->_models[$className]))
		{
			if(is_object($this->_models[$className]))
			{
				return $this->_models[$className];
			}
		}
		
        require APPLICATION_PATH . "/modules/admin/models/{$className}.php";
        $this->_models[$className] = new $className();        
        return $this->_models[$className];
    }
}